#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

#define E_ARGS      1
#define E_DIR       2
#define E_MEM       3
#define E_OUTFILE   4




int compare( const void* a, const void* b ) {

  return strcmp( *(char**)a, *(char**)b );

}  // END compare() //





int main( int argc, char* argv[] ) {

  DIR *dir = (DIR*)NULL;
  int n_entries = 0;
  char **entries = (char **)NULL;
  FILE* outfile = (FILE*)NULL;
  struct dirent *entry = (struct dirent *)NULL;
  int i = 0;                   // counter, etc. 
  char *prepend  = (char*)NULL;  // string to prepend to each entry
  char *playlist = (char*)NULL;  // string to use as playlist name


  if (argc != 3  &&  argc != 4) { 
    fprintf(stderr,"two or three arguments required.\n");
    // make your own error msg above
    exit(E_ARGS);
  }
  
  if (argc == 3) {
    prepend  = argv[1];
    playlist = argv[2];
  }
  else {
    prepend  = argv[2];
    playlist = argv[3];
  }

  dir = opendir( argv[1] );
  if (dir == (DIR*)NULL) {
    fprintf(stderr,"could not open directory %s\n",argv[1]);
    exit(E_DIR);
  }

  while ((entry=readdir(dir)) != (struct dirent *)NULL) {
    if ( *(entry->d_name) == '.' ) {
      continue;
    }
    n_entries++;
  }

  rewinddir(dir);
  
  entries = (char **) calloc(n_entries, sizeof(char*));
  if (entries == (char **)NULL) {
    fprintf(stderr,"memory allocation failed.\n");
    exit(E_MEM);
  }

  for (i=0; i<n_entries; i++) {
    entry = readdir(dir);
    
    if (entry == (struct dirent *)NULL) {
      fprintf(stderr,"files have been removed from the directory.\n");
      exit(-1);   // make your own error code
    }

    entries[i] = (char*) calloc( strlen(entry->d_name) + 1, sizeof(char));
    if (entries[i] == (char*)NULL) {
      fprintf(stderr,"out of memory.\n");
      exit(E_MEM);
    }

    if ( *(entry->d_name) == '.' ) {
      i--;
      continue;
    }

    strcpy( entries[i], entry->d_name );
  }

  qsort( entries, n_entries, sizeof(char*), compare );

  outfile = fopen(playlist,"w");
  if (outfile == (FILE*)NULL) {
    fprintf(stderr,"could not open playlist file.\n");
    exit(E_OUTFILE);
  }

  for (i=0; i<n_entries; i++) {
    fprintf(outfile,"%s%s\n",prepend,entries[i]);
  }

  // free memory
  for (i=0; i<n_entries; i++) {
    free( entries[i] );
  }
  free( entries );


  fclose( outfile );
  closedir( dir );

  exit(0);
} // END main() //



